package com.phpxiu.app.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.phpxiu.app.adapter.LiveHistoryListAdapter;
import com.phpxiu.app.adapter.holder.LiveHistoryViewHolder;
import com.phpxiu.app.api.callback.EnterRoomChecker;
import com.phpxiu.app.config.Constants;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.controller.avcontroller.QavsdkControl;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.CurLiveInfo;
import com.phpxiu.app.model.HistoryHost;
import com.phpxiu.app.model.LiveHistoryContent;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.model.UserHomeLiveInfo;
import com.phpxiu.app.model.list.LiveHistory;
import com.phpxiu.app.model.response.LiveHistoryModel;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.pulltorefresh.PullToRefreshListView;
import com.phpxiu.app.pulltorefresh.PullToRefreshView;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.RoomVideoRoom;
import com.phpxiu.app.view.UIHistoryVideoPlayer;
import com.phpxiu.app.view.custom.ListEmptyView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by WuJinZhou on 2016/6/6.
 */
public class UserHomeSecondFragment extends BaseFragment implements AdapterView.OnItemClickListener,PullToRefreshView.OnRefreshListener2<ListView>{
    public final static String TAG="UserHomeSecondFragment";
    public final static String UID="user_home_id";
    private final static int HANDLE_REFRESH_COMPLETE=0x1;
    private final static int HANDLE_REFRESH_LIST=0x2016;//刷新一第条数据，是否显示为正在直播
    private String uid;
    private List<LiveHistory>histories=new ArrayList<LiveHistory>();
    private PullToRefreshListView ptRefreshView;
    private ListView mListView;
    private LiveHistoryListAdapter mAdapter;
    private ListEmptyView emptyView;
    private int mOpera= HttpConfig.REQUEST_OPERA_INIT;
    private int pageSize=15;//每页取15条记录
    private int currentAllRecords=0;//当前列表刷新时获取的后台记录条数
    private int pageIndex=1;//下一页序号,页数从1开始计数
    private OKHttpParam param;
    private LiveHistoryContent baseContent=new LiveHistoryContent();
    private UserHomeLiveInfo mRoom;
    private LiveHistory liveItem=new LiveHistory(true);
    private String dateDistanceYMD;
    private String dateDaysSuffix;
    private String dateHoursSuffix;
    private String dateMinuteSuffix;
    private String dateDefaultSuffix;

    public static UserHomeSecondFragment builder(String uid){
        UserHomeSecondFragment fragment=new UserHomeSecondFragment();
        Bundle b = new Bundle();
        b.putString(UID,uid);
        fragment.setArguments(b);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initDateSuffix();
        uid=getArguments().getString(UID);
        KKYUtil.log("当前主页uid=" + uid);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView=inflater.inflate(R.layout.user_home_second_fragment,null);
        emptyView=new ListEmptyView(getActivity());
        emptyView.setMsg(getString(R.string.list_empty_title));
        init();
        return rootView;
    }

    /**
     * 初始化视图
     */
    private void init(){
        ptRefreshView=(PullToRefreshListView)rootView.findViewById(R.id.live_history_pull_refresh_list);
        ptRefreshView.setOnRefreshListener(this);
        mListView=ptRefreshView.getRefreshableView();
        mListView.setOnItemClickListener(this);
        mListView.setEmptyView(emptyView);
        mListView.setDivider(null);
        mAdapter=new LiveHistoryListAdapter(act,histories);
        mAdapter.initDateSuffix(dateDistanceYMD,dateDaysSuffix,dateHoursSuffix,dateMinuteSuffix,dateDefaultSuffix);
        mListView.setAdapter(mAdapter);
        request(mOpera);
    }

    private void initDateSuffix(){
        dateDistanceYMD=getString(R.string.date_distance_ymd);
        dateDaysSuffix=getString(R.string.date_distance_day_ago);
        dateHoursSuffix=getString(R.string.date_distance_hour_ago);
        dateMinuteSuffix=getString(R.string.date_distance_minute_ago);
        dateDefaultSuffix=getString(R.string.date_distance_default);
    }

    /**
     * 更新正在直播项数据
     * @param room 正在直播的房间信息
     */
    public void updateLive(UserHomeLiveInfo room){
        if(mRoom==null){
            mRoom=room;
            if(handler!=null){
                if("1".equals(mRoom.getStatus())){
                    handler.sendEmptyMessage(HANDLE_REFRESH_LIST);
                }
            }
        }
    }

    @Override
    public void handleMsg(Message msg) {
        switch (msg.what){
            case HANDLE_REFRESH_COMPLETE:
                if (ptRefreshView != null) {
                    ptRefreshView.onRefreshComplete();
                }
                break;
            case HANDLE_REFRESH_LIST:
                liveItem.setTitle(mRoom.getTitle());
                liveItem.setDate(mRoom.getTimeSpan());
                liveItem.setViewed(mRoom.getWatchCount());
                liveItem.setType(mRoom.getType());
                if(!histories.contains(liveItem)){
                    histories.add(0,liveItem);
                }
                mAdapter.notifyDataSetChanged();
                break;
        }
    }

    /**
     * 请求数据初始化
     */
    private void request(int opera){
        mOpera=opera;
        if(param==null){
            param= OKHttpParam.builder();
            param.put("pageSize",pageSize);
        }
        param.put("uid",uid);
        param.put("pageIndex",1);
        if(mOpera== HttpConfig.REQUEST_OPERA_LOAD){
            param.put("pageIndex",pageIndex==1?2:pageIndex);
        }
        OKHttp.post(HttpConfig.API_USER_HISTORY_LIST, param.jsonParam(), TAG, new OKHttpUIHandler(LiveHistoryModel.class) {
            @Override
            public void onSuccess(Object model) {
                emptyView.loaded();
                if (ptRefreshView != null) {
                    ptRefreshView.onRefreshComplete();
                }
                try {
                    LiveHistoryModel m = (LiveHistoryModel) model;
                    KKYUtil.log(TAG, "个人中心历史直播：" + m.getResponseStr());
                    if (mOpera == HttpConfig.REQUEST_OPERA_REFRESH || mOpera == HttpConfig.REQUEST_OPERA_INIT) {
                        histories.clear();
                        HistoryHost host = m.getData().getHost();
                        baseContent.setHostId(host.getUid());
                        baseContent.setLiveNo(host.getUid());
                        baseContent.setNick(host.getNickname());
                        baseContent.setAvatar(host.getAvatar());
                        baseContent.setTickets(host.getTotal_income());
                        currentAllRecords = m.getData().getTotalItem();
                        pageIndex = 1;
                    } else {
                        if (currentAllRecords > 0 && histories.size() > 0 && histories.size() < currentAllRecords) {
                            pageIndex++;
                        }
                    }
                    histories.addAll(m.getData().getVideolist());
                    if (mRoom != null && "1".equals(mRoom.getStatus())) {
                        liveItem.setTitle(mRoom.getTitle());
                        liveItem.setDate(mRoom.getTimeSpan());
                        liveItem.setViewed(mRoom.getWatchCount());
                        liveItem.setType(mRoom.getType());
                        if (!histories.contains(liveItem)) {
                            histories.add(0, liveItem);
                        }
                    }
                    mAdapter.notifyDataSetChanged();
                    listEmpty(histories.size() == 0);
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onErr(String errMsg) {
                if (ptRefreshView != null) {
                    ptRefreshView.onRefreshComplete();
                }
                listEmpty(histories.size() == 0);
            }
        });
    }

    /**
     * 进入直播间
     */
    public void onEnterRoom() {
        if(mRoom==null){
            KKYUtil.log(TAG, "个人中心直播间数据为空");
            return;
        }
        KKYUtil.log(TAG, "进入直播间：" + mRoom.getAvRoomId());
        if(QavsdkControl.getInstance().getAVContext()!=null){
        }else{
            Toast.makeText(getActivity(),getString(R.string.join_room_failed),Toast.LENGTH_LONG).show();
            EnterRoomChecker.getInstance().IMLogin(MySelfInfo.getInstance().getId(), MySelfInfo.getInstance().getUserSig());//重新登录
            return;
        }
        try {
            //如果是自己
            if (mRoom.getHost().getUid().equals(MySelfInfo.getInstance().getId())) {
                Toast.makeText(getActivity(), getString(R.string.join_room_failed), Toast.LENGTH_SHORT).show();
                return;
            }
            Intent intent = new Intent(getActivity(), RoomVideoRoom.class);
            intent.putExtra(Constants.ID_STATUS, Constants.MEMBER);
            MySelfInfo.getInstance().setIdStatus(Constants.MEMBER);
            CurLiveInfo.setHostID(mRoom.getHost().getUid());
            CurLiveInfo.setHostName(mRoom.getHost().getNickname());
            CurLiveInfo.setHostAvator(mRoom.getHost().getAvatar());
            CurLiveInfo.setRoomNum(Integer.parseInt(mRoom.getAvRoomId()));
            CurLiveInfo.setMembers(Integer.parseInt(mRoom.getWatchCount()) + 1); // 添加自己
            CurLiveInfo.setAdmires(Integer.parseInt(mRoom.getAdmireCount()));
            CurLiveInfo.setAddress(mRoom.getLbs().getAddress());
            startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if(view.getTag()!=null&&view.getTag() instanceof LiveHistoryViewHolder){
                LiveHistory history=((LiveHistoryViewHolder)view.getTag()).getHistory();
                if(history.isLive()){
                    //观看直播
                    onEnterRoom();
                }else{
                    Intent play=new Intent(getContext(), UIHistoryVideoPlayer.class);
                    baseContent.setLiveTitle(history.getTitle());
                    baseContent.setVideoUrl(history.getUrl());
                    baseContent.setWatchCount(history.getViewed());
                    play.putExtra(UIHistoryVideoPlayer.LIVE_INFO,baseContent);
                    startActivity(play);
                }
            }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshView<ListView> refreshView) {
        request(HttpConfig.REQUEST_OPERA_REFRESH);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshView<ListView> refreshView) {
        if(histories.size()!=0&&histories.size()<currentAllRecords) {
            request(HttpConfig.REQUEST_OPERA_LOAD);
        }else{
            handler.sendEmptyMessage(HANDLE_REFRESH_COMPLETE);
        }
    }

    /**
     * 空列表,不加载更多
     */
    public void listEmpty(boolean isEmpty){
        if (ptRefreshView != null) {
            if(isEmpty) {
                ptRefreshView.setMode(PullToRefreshView.Mode.PULL_FROM_START);
            }else{
                ptRefreshView.setMode(PullToRefreshView.Mode.BOTH);
            }
        }
    }
}
